package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.generated.tables.records.UserRecord;
import com.mai4j.maiadmin.misc.DbUtils;
import com.mai4j.maiadmin.model.dto.PageDTO;
import com.mai4j.maiadmin.model.dto.UserDTO;
import com.mai4j.maiadmin.model.http.datatables.Datatable;
import com.mai4j.maiadmin.model.http.datatables.Search;
import com.mai4j.maiadmin.service.UserGroupService;
import com.mai4j.maiadmin.service.UserService;
import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.support.i18n.I18n;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.SelectWhereStep;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static com.mai4j.maiadmin.generated.Tables.USER;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserGroupService userGroupService;

    public UserServiceImpl(UserGroupService userGroupService) {
        this.userGroupService = userGroupService;
    }

    @Override
    public PageDTO<UserDTO> paginate(Datatable datatable) {
        DSLContext dsl = JooqProvider.dsl();
        SelectWhereStep<UserRecord> query = dsl.selectFrom(USER);
        String value = Optional.ofNullable(datatable.getSearch()).orElse(new Search()).getValue();
        List<Condition> conditions = new ArrayList<>();
        if (StringUtils.isNotBlank(value)) {
            value = "%" + value + "%";
            conditions.add(USER.NAME.like(value).or(USER.EMAIL.like(value)).or(USER.ACCOUNT.like(value)).or(USER.TELEPHONE.like(value)));
        }
        query.where(conditions);
        int count = dsl.fetchCount(query);
        List<UserDTO> userDTOS = count == 0 ? Collections.emptyList() : query
                .orderBy(USER.USER_ID)
                .limit(datatable.getStart(), datatable.getLength())
                .fetchInto(UserDTO.class);
        userDTOS.forEach(u -> u.setUserGroup(this.userGroupService.get(u.getUserGroupId(), I18n.getTag())));
        return new PageDTO<>(userDTOS, DbUtils.getPage(datatable), datatable.getLength(), DbUtils.getTotalPage(count, datatable), count);
    }
}
